package com.cn.server.module.login.handler;

import com.cn.common.core.exception.ErrorCodeException;
import com.cn.common.core.exception.ErrorResponse;
import com.cn.common.core.model.Result;
import com.cn.common.core.model.ResultCode;
import com.cn.common.core.serial.Serializer;
import com.cn.common.core.session.Session;
import com.cn.common.module.login.request.LoginRequest;
import com.cn.common.module.login.response.LoginResponse;
import com.cn.server.Constant;
import com.cn.server.module.login.service.UserService;
import com.cn.server.module.login.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 用户模块
 */
public class UserHandlerImpl implements UserHandler {

    private UserService userService = new UserServiceImpl();


    @Override
    public <T extends Serializer> Result login(Session session, byte[] data) {
        LoginResponse result = null;
        try {
            //反序列化
            LoginRequest loginRequest = new LoginRequest();
            loginRequest.readFromBytes(data);

            //参数判空
            if (StringUtils.isEmpty(loginRequest.getLoginName()) || StringUtils.isEmpty(loginRequest.getToken())) {
                return Result.ERROR(new ErrorResponse(ResultCode.LOGINNAME_NULL, Constant.LOGINNAME_NULL));
            }

            //执行业务
            result = userService.login(session, loginRequest.getLoginName(), loginRequest.getToken());
            return Result.SUCCESS(result);
        } catch (ErrorCodeException e) {
            return Result.ERROR(new ErrorResponse(e.getErrorCode(), e.getErrorReason()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(new ErrorResponse(ResultCode.UNKOWN_EXCEPTION, Constant.SYSTEM_ERROR));
        }
    }

}
